import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STChange, STColumn, STComponent, STData, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFUISchema } from '@delon/form';
import { SearchDrawerService, ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BasicTableComponent } from 'src/app/routes/commom';
import { ReportingService } from '../../services/reporting.service';
import { DatatableReportingUploadSettingComponent } from '../upload-setting/upload-setting.component';
import { DatatableReportingVerifyResultComponent } from '../verify-result/verify-result.component';
import { DatatableReportingvViewTrackComponent } from '../view-track/view-track.component';

@Component({
  selector: 'app-datatable-order-reporting',
  templateUrl: './order-reporting.component.html',
  styleUrls: ['../../../../commom/less/commom-table.less', './order-reporting.component.less']
})
export class DatatableOrderReportingComponent extends BasicTableComponent implements OnInit {
  columns!: STColumn[];
  tabType!: string;
  tabs: any[] = [
    { name: '待上传', value: '0' },
    { name: '上传中', value: '3' },
    { name: '已上传', value: '1' },
    { name: '异常', value: '2' },
    { name: '全部', value: '' }
  ];
  selectedIndex = '0';
  isLoading: boolean = false;
  selectedRows: any[] = [];
  netWorkList: any[] = [
    {
      enterpriseName: '全部',
      id: ''
    }
  ];
  constructor(
    public service: ReportingService,
    private router: Router,
    private ar: ActivatedRoute,
    private modal: NzModalService,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
    this.sfValue = { networkTransporter: '1516592797585588226' };
  }

  /**
   * 查询参数
   */
  get reqParams() {
    const params = Object.assign({}, this.sf?.value || {}, {
      billPutStatus: this.selectedIndex
    });
    delete params._$expand;
    return { ...params };
  }

  /**
   * 选中行
   */
  // get selectedRows() {
  //   return this.st?.list.filter((item: any) => item.checked) || [];
  // }

  /**
   * 程序初始化入口
   */
  ngOnInit() {
    this.initSF();
    this.initST();
    console.log(this.service.getNetworkFreightForwarder({}, false));
    this.service.request(this.service.$api_get_network_freight_forwarder_list, {}).subscribe((res: any) => {
      console.log(res);
      this.netWorkList.push(...res);
    });
  }

  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        billCode: { title: '订单号', type: 'string', ui: { placeholder: '请输入' } },
        wayBillCode: {
          type: 'string',
          title: '运单号',
          ui: {
            placeholder: '请输入'
          }
        },
        // networkTransporter: {
        //   title: '网络货运人',
        //   type: 'string',
        //   ui: {
        //     placeholder: '请选择',
        //     widget: 'select',
        //     asyncData: () => this.service.getNetworkFreightForwarder({}, false),
        //     allowClear: true
        //   },
        //   default: '1516592797585588226'
        // },
        shipperName: {
          title: '货主',
          type: 'string',
          ui: {
            placeholder: '请输入'
          }
        },
        driverName: {
          title: '承运司机',
          type: 'string',
          ui: {
            placeholder: '请输入司机姓名/手机号'
          }
        },
        carNo: {
          title: '车牌号',
          type: 'string',
          maxLength: 9,
          ui: {
            placeholder: '请输入'
          }
        },
        // putStatus: {
        //   title: '上传状态',
        //   type: 'string',
        //   default: 0,
        //   enum: [
        //     { label: '待上传', value: 0 },
        //     { label: '已上传', value: 1 },
        //     { label: '异常', value: 2 }
        //   ],

        //   ui: {
        //     placeholder: '请选择',
        //     widget: 'select',
        //     allowClear: true,
        //     visibleIf: {
        //       _$expand: (value: boolean) => value,
        //     },
        //   }
        // },
        checkStatus: {
          title: '本地校验',
          type: 'string',
          enum: [
            { label: '检测中', value: 0 },
            { label: '通过', value: 1 },
            { label: '不通过', value: 2 }
          ],
          ui: {
            placeholder: '请选择',
            widget: 'select',
            allowClear: true
          }
        },
        recentlyPutTime: {
          title: '上传时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        orderPayTime: {
          title: '核销时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        orderReceivingTime: {
          title: '运单生成时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        dispatchedDate: {
          title: '发货时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        receivingDate: {
          title: '收货时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },

        trajectoryDataAppStatus: {
          title: '车辆轨迹',
          type: 'string',
          enum: [
            { label: '全部', value: '' },
            { label: '有', value: '1' },
            { label: '无', value: '0' }
          ],
          ui: {
            placeholder: '请选择',
            widget: 'select'
          }
        },
        trajectoryDataStatus: {
          title: '司机轨迹',
          type: 'string',
          enum: [
            { label: '全部', value: '' },
            { label: '有', value: '1' },
            { label: '无', value: '0' }
          ],
          ui: {
            placeholder: '请选择',
            widget: 'select'
          }
        }
      }
    };
  }

  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', className: 'text-center', width: '60px' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return (this.st.pi * this.st.ps) - this.st.ps + idx + 1 + ''
        }
      },
      { title: '上传状态', render: 'billPutStatus', className: 'text-center', width: '120px' },
      // { title: '司机状态', index: 'driverPutStatusLabel', className: 'text-center', width: '120px' },
      // { title: '车辆状态', index: 'carPutStatusLabel', className: 'text-center', width: '120px' },
      { title: '本地校验', render: 'checkStatus', className: 'text-center', width: '120px' },
      {
        title: '订单号',
        render: 'billCode',
        className: 'text-center',
        width: '180px'
      },
      { title: '运单号', render: 'wayBillCode', className: 'text-center', width: '180px' },

      {
        title: '网络货运人',
        index: 'enterpriseInfoName',
        className: 'text-center',
        width: '180px'
      },
      { title: '托运人名称', index: 'shipperName', className: 'text-center', width: '250px' },
      // { title: '统一社会信用代码', index: 'unifiedSocialCreditCode', className: 'text-center', width: '200px' },
      { title: '运单生成时间', index: 'wayBillCreateTime', className: 'text-center', width: '180px' },
      { title: '发货时间', index: 'dispatchedDate', className: 'text-center', width: '180px' },
      { title: '收货时间', index: 'receivingDate', className: 'text-center', width: '180px' },

      // { title: '托运人统一社会信用代码', index: 'shipperCreditCode', className: 'text-center', width: '200px' },
      { title: '装货地址', index: 'loadingAddress', className: 'text-center', width: '200px' },
      { title: '收货方名称', index: 'receivingName', className: 'text-center', width: '150px' },
      { title: '收货地址', index: 'consigneeAddress', className: 'text-center', width: '150px' },
      { title: '运费金额', render: 'freightAmount', className: 'text-center', width: '130px' },
      { title: '车牌号', index: 'carNo', className: 'text-center', width: '150px' },
      {
        title: '车牌颜色',
        index: 'carNoColor',
        className: 'text-center',
        width: '250px',
        type: 'enum',
        enum: {
          '4': '绿色',
          '3': '黄绿色',
          '2': '黄色',
          '1': '蓝色'
        }
      },
      { title: '司机姓名', index: 'driverName', className: 'text-center', width: '150px' },
      { title: '司机手机号码', index: 'driverPhone', className: 'text-center', width: '200px' },
      { title: '司机身份证号', index: 'driverIdentityNo', className: 'text-center', width: '150px' },
      { title: '货物信息', index: 'goodsName', className: 'text-center', width: '180px' },
      { title: '实际承运人名称', index: 'carrierName', className: 'text-center', width: '150px' },
      { title: '实际承运人证件号码', index: 'carrierIdentityNo', className: 'text-center', width: '200px' },
      // { title: '实际承运人道路运输许可证号', index: 'roadTransportNo', className: 'text-center', width: '230px' },
      { title: '车辆轨迹', render: 'car', className: 'text-center', width: '250px' },
      { title: '司机轨迹', render: 'driver', className: 'text-center', width: '150px' },
      { title: '上传次数', index: 'putNumber', className: 'text-center', width: '150px' },
      { title: '上传时间', index: 'recentlyPutTime', className: 'text-center', width: '180px' }
    ];
  }

  /**
   *撤销
   * @param record 记录实例
   */
  recall() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要撤回的数据');
      return;
    }
    this.modal.confirm({
      nzTitle: '撤回提示',
      nzContent: '撤回后可以重新上传，重新上传会覆盖已上传数据，确定要撤回？',
      nzOkText: '确定',
      nzCancelText: '取消',
      nzOnOk: () => {
        const ids = this.selectedRows.map(i => i?.id);
        this.service.request(this.service.$api_recall_order_reporting, ids).subscribe((res: any) => {
          if (res) {
            this.service.msgSrv.success('撤销成功');
            this.search();
          }
        });
      }
    });
  }

  changeSt(e: STChange): void {
    if (e.type === 'checkbox') {
      const checkRows = (e.checkbox as STData[]) || [];
      //判断当前页是否有选中的行
      if (checkRows.length === 0) {
        // 当前页没有存在已勾选的行，移除之前所记录的当前页的行
        const stList = this.st.list;
        stList.forEach(item => {
          this.selectedRows = this.selectedRows.filter((e: any) => e.id !== item.id);
        });
      } else {
        //添加新增的行
        checkRows.forEach((item: any) => {
          const newSelectedList = this.selectedRows.filter((r: any) => r.id === item.id);
          if (newSelectedList.length === 0) {
            this.selectedRows.push(item);
          }
        });
        // 移除取消选中的行
        const stList = this.st.list;
        stList.forEach(item => {
          if (!item.checked) {
            const index = this.selectedRows.findIndex(_item => item.id === _item.id);
            if (index !== -1) this.selectedRows.splice(index, 1);
          }
        });
      }
    } else if (e.type === 'loaded') {
      // 页面加载时勾选
      (e?.loaded || []).forEach((r: any) => {
        this.selectedRows.forEach(x => {
          if (x.id === r.id) {
            r.checked = true;
          }
        });
      });
    }
  }
  beforeReq = (requestOptions: STRequestOptions) => {
    Object.assign(requestOptions.body, { listSource: 1 });
    if (this.sfValue) {
      Object.assign(requestOptions.body, {
        ...this.sfValue,
        billPutStatus: this.selectedIndex
      });
    }
    // this.loadingList = true;
    return requestOptions;
  };

  dataProcess = (data: STData[]): STData[] => {
    // this.loadingList = false;
    return data;
  };
  selectChange(item: any) {
    this.selectedIndex = item?.value || '';
    setTimeout(() => {
      this.selectedRows = [];
      this.st.load(1);
    });
  }

  /**
   * 查看当行数据
   */
  view(record: STData) {
    // this.router.navigate(['../view', record.uuid], { relativeTo: this.ar });
    this.router.navigate(['../detail'], {
      queryParams: {
        id: record.id
      },
      relativeTo: this.ar
    });
  }

  // appeal(item: any) {
  //   const modalRef = this.modal.create({
  //     nzTitle: '申诉',
  //     nzWidth: '40%',
  //     nzContent: CtcAppealComponent,
  //     nzComponentParams: {
  //       i: item,
  //       status: 'add'
  //     },
  //     nzFooter: null
  //   });
  //   modalRef.afterClose.subscribe(res => {
  //     if (res) {
  //       this.search({ representationsStatus: '' });
  //     }
  //   })
  // }

  /**
   * 上传
   */
  upload() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要上传的数据');
      return;
    }
    let status = true;
    this.selectedRows.forEach((i: any) => {
      if (i?.billPutStatus == '1') {
        status = false;
      }
    });
    if (!status) {
      this.openWainingModal('已上传的数据不能再次上传！');
      return;
    }
    const ids = this.selectedRows.map(i => i?.id);
    this.service.request(this.service.$api_upload_order_reporting, ids).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('上传成功');
        this.search();
      }
    });
  }

  /**
   *
   * @param params 上传设置
   */
  uploadSetting() {
    const modalRef = this.modal.create({
      nzTitle: '上传设置',
      nzWidth: 600,
      nzContent: DatatableReportingUploadSettingComponent,
      nzComponentParams: {},
      nzFooter: null
    });
    modalRef.afterClose.subscribe(res => {});
  }

  /**
   * 查看校验结果
   */
  viewResult(item: any) {
    const modalRef = this.modal.create({
      nzTitle: '校验结果',
      nzWidth: 1200,
      nzContent: DatatableReportingVerifyResultComponent,
      nzComponentParams: {
        record: item
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe(res => {});
  }

  /**
   * 查看监管审核结果
   */
  viewAuditResult(record: any) {
    this.openWainingModal(record?.exceptionInfo);
  }

  search() {
    this.selectedRows = [];
    this.st.load(1);
  }

  /**
   * 异步导出
   */
  export() {
    this.service.exportStart({ ...this.sf?.value, pageSize: -1 }, this.service.$api_export_reporting_order);
  }

  openWainingModal(content: string, title = '提示') {
    this.modal.warning({
      nzMask: false,
      nzTitle: title,
      nzContent: content
    });
  }

  /**
   * 查看轨迹
   */
  viewTrack(_record: any, trajectory: string) {
    const title = trajectory === 'car' ? '车辆' : '司机';
    const modalRef = this.modal.create({
      nzTitle: `查看${title}轨迹`,
      nzWidth: 620,
      nzContent: DatatableReportingvViewTrackComponent,
      nzComponentParams: {
        id: _record?.orderId,
        trajectory
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe(res => {});
  }

  /**
   * 更新数据
   */
  updateData() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要更新的数据');
      return;
    }
    let status = true;
    this.selectedRows.forEach((i: any) => {
      if (i?.billPutStatus == '1') {
        status = false;
      }
    });
    if (!status) {
      this.openWainingModal('已上传的数据不能更新！');
      return;
    }
    const ids = this.selectedRows.map(i => i?.orderId);
    this.service.request(this.service.$api_update_order_data, ids).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('更新成功');
        this.selectedRows = [];
        this.st.reload();
      }
    });
  }

  /**
   * 异常通过
   */
  exceptionCross() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要异常通过的订单');
      return;
    }
    const ids = this.selectedRows.map(i => i?.id);
    this.service.request(this.service.$api_exception_cross, ids).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('已通过');
        this.selectedRows = [];
        this.st.reload();
      }
    });
  }

  /**
   * 生成资金
   */
  createZjUpload() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要生成资金上传的数据');
      return;
    }
    const ids = this.selectedRows.map(i => i?.orderId);
    this.service.request(this.service.$api_create_zjupload, ids).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('成功');
        this.selectedRows = [];
        this.st.reload();
      }
    });
  }

  filterStatus(status: number) {
    switch (status) {
      case 0:
        return '待上传';
      case 1:
        return '已上传';
      case 2:
        return '上传异常';
      default:
        return '';
    }
  }

  filterCheckStatus(status: string | number) {
    switch (status) {
      case '0':
        return '检测中';
      case '1':
        return '通过';
      case '2':
        return '不通过';
      default:
        return '';
    }
  }

  routeToOrder(item: any) {
    if (item.billType === '1') {
      window.open(location.origin + `/#/order-management/vehicle/vehicle-detail/${item.orderId}`);
    } else if (item.billType === '2') {
      window.open(location.origin + `/#/order-management/bulk/bulk-detail/${item.orderId}`);
    } else if (item.billType === '3') {
      window.open(location.origin + `/#/order-management/vehicle/vehicle-detail/${item.orderId}`);
    }
  }

  routeTowaybill(item: any) {
    if (item.billType === '1') {
      window.open(location.origin + `/#/waybill-management/vehicle/vehicle-detail/${item.waybillId}`);
    } else if (item.billType === '2') {
      window.open(location.origin + `/#/waybill-management/bulk/bulk-detail/${item.waybillId}`);
    } else if (item.billType === '3') {
      window.open(location.origin + `/#/waybill-management/vehicle/vehicle-detail/${item.waybillId}`);
    }
  }
}
